package com.everflourish.yeah100.act.markingsystem;

import android.bluetooth.BluetoothDevice;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.Toolbar;
import android.view.KeyEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.base.BaseActivity;
import com.everflourish.yeah100.adapter.MarkingViewPagerAdapter;
import com.everflourish.yeah100.entity.Examination;
import com.everflourish.yeah100.entity.marking.ReadCardRecord;
import com.everflourish.yeah100.ui.XListView;
import com.everflourish.yeah100.ui.dialog.BluetoothDeviceDialog;
import com.everflourish.yeah100.ui.dialog.LoadDialog;
import com.everflourish.yeah100.utils.CommonUtil;
import com.everflourish.yeah100.utils.DateFormatUtil;
import com.everflourish.yeah100.utils.IntentUtil;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.bluetooth.BluetoothCommand;
import com.everflourish.yeah100.utils.bluetooth.BluetoothHelper;
import com.everflourish.yeah100.utils.bluetooth.IBluetoothSearch;
import com.everflourish.yeah100.utils.bluetooth.IBluetoothStatus;
import com.everflourish.yeah100.utils.bluetooth.IReadCard;
import com.everflourish.yeah100.utils.constant.RecordType;
import com.everflourish.yeah100.utils.constant.SheetType;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 作者：Created by Administrator on 2016/6/3.
 * 时间：2016/6/3
 */
public class MarkingMenuActivity extends BaseActivity implements ViewPager.OnPageChangeListener {

    // 蓝牙部分
    /**
     * 读卡的标记，判断是读取标准答案（1），还是读取学生成绩（2）
     */
    public int mReadFlag = NOT_READ_FLAG;
    public static final int NOT_READ_FLAG = -1;
    public static final int STANDARD_FLAG = 1;
    public static final int STUDENT_FLAG = 2;
    public static final int SINGLE_STUDENT_FLAG = 3;

    private Toolbar mToolBar;
    private TabLayout mTabLayout;
    public ViewPager mViewPager;
    //    private MarkingMenuActivity mActivity;
    private FragmentManager mFragmentManager;
    private List<Fragment> mFragments;
    public FragmentExamCreate mFragmentExamCreate;
    public FragmentTopicSetting mFragmentTopicSetting;
    public FragmentStandardAnswer mFragmentStandardAnswer;
    public static FragmentReadPaper mFragmentReadPaper;
    public FragmentExamCreate mFragmentReadPaper2;
    public FragmentProofreading fragmentProofreading;
    private MarkingViewPagerAdapter mMarkingViewPagerAdapter;
    private String[] mTitles;
    public static Examination mExamination;
    public static boolean isUpdateExamination = false;
    private LoadDialog mLoadDialog;
    public BluetoothHelper mBluetoothHelper;
    private int checkFlag;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_marking_menu);
        initData();
        initBluetooth();
        initFragment();
        initView();
        configView();
    }

    private void initData() {
        mExamination = (Examination) getIntent().getSerializableExtra(
                IntentUtil.EXAMINATION);
        checkFlag = getIntent().getIntExtra("flag", 0);
        mFragmentManager = getSupportFragmentManager();
        mTitles = getResources().getStringArray(R.array.tab_titles);
    }

    private void initBluetooth() {
        mBluetoothHelper = BluetoothHelper.getInstance(mContext);
        // 接口回调
        mBluetoothHelper.setOnReadCardListener(iReadCard);
        mBluetoothHelper.setOnBluetoothSearchListener(iBluetoothSearch);
        mBluetoothHelper.setOnBluetoothStatusListener(iBluetoothStatus);
    }

    private void initFragment() {
        mFragments = new ArrayList<Fragment>();
        mFragmentExamCreate = new FragmentExamCreate();
        mFragmentTopicSetting = new FragmentTopicSetting();
        mFragmentStandardAnswer = new FragmentStandardAnswer();
        mFragmentReadPaper = new FragmentReadPaper();
        mFragmentReadPaper2 = new FragmentExamCreate();
        fragmentProofreading = new FragmentProofreading();

        mFragments.add(mFragmentExamCreate);
        mFragments.add(mFragmentTopicSetting);
        mFragments.add(mFragmentStandardAnswer);
        mFragments.add(mFragmentReadPaper);
        mFragments.add(fragmentProofreading);
    }

    private void initView() {
        mToolBar = (Toolbar) findViewById(R.id.toolbar_marking);
        mTabLayout = (TabLayout) findViewById(R.id.tab_marking);
        mViewPager = (ViewPager) findViewById(R.id.viewpager_marking);
        mMarkingViewPagerAdapter = new MarkingViewPagerAdapter(getSupportFragmentManager(), mTitles, mFragments);
        mViewPager.setAdapter(mMarkingViewPagerAdapter);
        mViewPager.setCurrentItem(checkFlag);
        if (checkFlag == 0) {
            mToolBar.setTitle("基础信息");
        } else if (checkFlag == 1) {
            mToolBar.setTitle("题型设置");
        } else if (checkFlag == 2) {
            mToolBar.setTitle("标准答案");
        } else if (checkFlag == 3) {
            mToolBar.setTitle("蓝牙阅卷");
        }else if (checkFlag == 4){
            mToolBar.setTitle("校对数据");
        }
        // 在setAdapter之后调用
        mViewPager.setOffscreenPageLimit(5);
        mViewPager.addOnPageChangeListener(this);
        mTabLayout.setupWithViewPager(mViewPager);
//        mTabLayout.setTabMode(TabLayout.MODE_SCROLLABLE);
        mTabLayout.setTabsFromPagerAdapter(mMarkingViewPagerAdapter);
    }

    private void configView() {
//        mToolBar.setTitle("基础信息");
        setSupportActionBar(mToolBar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        mToolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (showExitWarn()) {
                    return;
                }
                finishMenuActivity();
            }
        });
    }

    private void finishMenuActivity() {
        if (mBluetoothHelper.isConn) {
            mBluetoothHelper.setCloseBluetooth(true);
            mBluetoothHelper.closeConnectBluetooth();
        }
//        mBluetoothHelper.isConn = false;
        Intent resultIntent = getIntent();
        resultIntent.putExtra(IntentUtil.IS_UPDATE, isUpdateExamination);
        this.setResult(RESULT_OK, resultIntent);
        IntentUtil.finishActivity(MarkingMenuActivity.this);
    }

    @Override
    public void onPageSelected(int position) {
        mReadFlag = NOT_READ_FLAG;
        mFragmentReadPaper.mStuReadCardBt.setText("读卡");
        mFragmentStandardAnswer.mReadCardBt.setText("读卡");
        mToolBar.setTitle(mTitles[position]);
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mQueue != null) {
            mQueue.stop();
        }
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (showExitWarn()) {
                return true;
            }
            finishMenuActivity();
            return true;
        } else {
            return super.onKeyUp(keyCode, event);
        }
    }

    private boolean showExitWarn() {
        if (mFragmentExamCreate.setIsChange()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setMessage("基础信息未保存，是否要继续退出？");
            builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                    finishMenuActivity();
                }
            });
            builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            });
            builder.show();
            return true;
        }
        return false;
    }

    /**************************************蓝牙回调部分************************************************/

    /**
     * 提示是否打开蓝牙
     */
    public void openBluetooth() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("没有连接阅卷机，是否开启蓝牙连接？");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                mBluetoothHelper.connectBluetooth(MarkingMenuActivity.this);
                dialog.dismiss();
            }
        });
        builder.setNegativeButton("否", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.show();
    }

    /**
     * 蓝牙连接状态监听
     */
    IBluetoothStatus iBluetoothStatus = new IBluetoothStatus() {
        @Override
        public void connBluetoonthFailure(boolean isConn, Exception e) {
            LoadDialog.dismiss(mLoadDialog);
            MyToast.showShort(mContext, "连接蓝牙失败");
        }

        @Override
        public void connBluetoonthChange(boolean isConn) {
            LoadDialog.dismiss(mLoadDialog);
            if (isConn) {
                MyToast.showShort(mContext, "连接蓝牙成功!");
//                setConnectedAnim();
            } else {
                if (mBluetoothHelper.isCloseBluetooth()) {
                    MyToast.showShort(mContext, "已断开蓝牙连接!");
                }
                if (mFragmentReadPaper != null) {
                    mFragmentReadPaper.readCard(1, false);
                }
                if (mFragmentStandardAnswer != null) {
                    mFragmentStandardAnswer.setDisconnectStatus();
                }
            }
        }
    };

    /**
     * 蓝牙设备搜索监听
     */
    IBluetoothSearch iBluetoothSearch = new IBluetoothSearch() {
        List<BluetoothDevice> devices;
        BluetoothDeviceDialog deviceDialog = null;
        List<String> items;

        @Override
        public void start(final List<BluetoothDevice> pairedDevices) {
            devices = new ArrayList<BluetoothDevice>();
            deviceDialog = new BluetoothDeviceDialog(mContext, "蓝牙列表");
            items = new ArrayList<String>();
            for (BluetoothDevice b : pairedDevices) {
                if (CommonUtil.isCRMachine(b.getName())) {
                    devices.add(b);
                    items.add(b.getName());
                }
            }
            deviceDialog.setItems(items, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mBluetoothHelper.cancleDiscovery();
                    // 点击连接蓝牙
                    BluetoothDevice bluetoothDevice = devices.get(which - 1);
                    showConnDialog(bluetoothDevice);
                    mBluetoothHelper.connect(bluetoothDevice.getAddress());
                }
            });
            deviceDialog
                    .setXListViewListener(new XListView.IXListViewListener() {
                        @Override
                        public void onRefresh() {
                        }

                        @Override
                        public void onLoadMore() {
                            mBluetoothHelper.searchBluetooh();
                        }
                    });
            deviceDialog
                    .setOnCancelListener(new DialogInterface.OnCancelListener() {
                        @Override
                        public void onCancel(DialogInterface dialog) {
                            // 当对话框被取消了，立即结束蓝牙搜索
                            mBluetoothHelper.cancleDiscovery();
                        }
                    });
            deviceDialog.show();
        }

        @Override
        public void found(BluetoothDevice newDevice) {
//            MyToast.showLong(mContext, newDevice.getName());
            for (BluetoothDevice d : devices) {
//                MyToast.showLong(mContext, newDevice.getName());
                if (newDevice.getAddress().equals(d.getAddress())) {
                    return;
                }
            }
            if (CommonUtil.isCRMachine(newDevice.getName())) {
                devices.add(newDevice);
                items.add(newDevice.getName());
            }
            deviceDialog.notifyDataSetChanged();
        }

        @Override
        public void complete(List<BluetoothDevice> newDevices) {
            deviceDialog.stopLoadMore();
            Toast.makeText(mContext, "搜索结束！", Toast.LENGTH_LONG).show();
        }
    };

    public void readStandardAnswer(TextView tv) {
        mReadFlag = STANDARD_FLAG;
        tv.setText("等待读卡...");
    }

    /**
     * 蓝牙阅卷监听
     */
    IReadCard iReadCard = new IReadCard() {
        @Override
        public void readFailure() {
            String msg = "读取答题卡失败!";
            record(msg, RecordType.read_card_failure);
            record("读取答题卡失败，点击查看帮助!", RecordType.read_failure_help);
            mFragmentReadPaper.showReadCardInfo(null);
            sendCommandForBackward();
        }

        @Override
        public void readSuccess(SheetType sheetType, Map<String, Object> map) {
            // 读卡成功，一个是读取标准答案，一个是读取学生的答案
            if (mReadFlag == STANDARD_FLAG && mViewPager.getCurrentItem() == 2) {
                // 读标准答案
//                LoadDialog.dismiss(mLoadDialog);
                mFragmentStandardAnswer.readComplete(map);
            } else if (mReadFlag == STUDENT_FLAG && mViewPager.getCurrentItem() == 3) {
                // 读学生答案
                mFragmentReadPaper.readComplete(map);
            } else if (mReadFlag == SINGLE_STUDENT_FLAG) {
                // 读取单个学生的成绩，学生的客观题答案界面
//                LoadDialog.dismiss(mLoadDialog);
                mFragmentReadPaper.readComplete(map);
            }
        }

        @Override
        public void notFoundSheet() {
            // 处理答题卡类型没有找到
            if (mReadFlag == STANDARD_FLAG && mViewPager.getCurrentItem() == 2) {
                // 读标准答案
                readCardFailure();
            } else if (mReadFlag == SINGLE_STUDENT_FLAG) {
                readCardFailure();
            } else if (mReadFlag == STUDENT_FLAG && mViewPager.getCurrentItem() == 3) {
                String msg = "读取答题卡失败!";
                record(msg, RecordType.read_card_failure);
                record("读取答题卡失败，点击查看帮助!", RecordType.read_failure_help);
                // mFragmentReadPaper.mFragmentReadSub.setData(null);
                mFragmentReadPaper.showReadCardInfo(null);
            }
            sendCommandForBackward();
        }
    };

    private void showConnDialog(BluetoothDevice bluetoothDevice) {
        mLoadDialog = LoadDialog.show(mContext, bluetoothDevice.getName(),
                "正在连接阅卷机...", false,
                new DialogInterface.OnCancelListener() {
                    @Override
                    public void onCancel(DialogInterface dialog) {
                        mBluetoothHelper.setCloseBluetooth(false);
                        mBluetoothHelper.closeConnectBluetooth();
                    }
                });
    }

    /**
     * 没有找到对应的答题卡类型
     */
    public void readCardFailure() {
        StringBuffer msgSb = new StringBuffer();
        msgSb.append("1.请检查答题卡是否有缺失").append("\n");
        if (mBluetoothHelper.isConn) {
            msgSb.append("2.阅卷机和手机的距离尽量保持在3米内").append("\n");
            msgSb.append("3.如果多次读答题卡失败可以尝试重新连接").append("\n");
            msgSb.append("4.请检查是否支持当前的答题卡").append("\n");
            msgSb.append("5.连接的阅卷机是否正确，如下图!").append("\n");
            AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
            builder.setTitle("读卡失败");
            builder.setMessage(msgSb.toString());
            builder.setPositiveButton("重新连接", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    mBluetoothHelper.setCloseBluetooth(false);
                    mBluetoothHelper.closeConnectBluetooth();
                    //TODO
//                    showConnDialog(mBluetoothHelper.mConnDevice);
                    mBluetoothHelper
                            .connect(mBluetoothHelper.mConnDevice
                                    .getAddress());
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton("关闭", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {

                }
            });
            builder.show();
        }
    }

    /**
     * 添加一个读卡记录
     *
     * @param msg
     * @param recordType
     */
    public void record(String msg, RecordType recordType) {
//        FragmentStudentDetailAnswer fragmentReadSub = mFragmentReadPaper.mFragmentReadSub;
        List<ReadCardRecord> recordList = mFragmentReadPaper.mRecordList;
        if (CommonUtil.isHelpType(recordType)) {
            for (ReadCardRecord r : recordList) {
                if (CommonUtil.isHelpType(r.getRecordType())) {
                    r.setMsg(msg);
                    r.setRecordType(recordType);
//                    if (fragmentReadSub != null) {
                    // fragmentReadSub.mAdapter.notifyDataSetChanged();
//                    }
                    return;
                }
            }
        } else if (recordType == RecordType.read_card_success) {
            for (ReadCardRecord r : recordList) {
                if (CommonUtil.isHelpType(r.getRecordType())) {
                    recordList.remove(r);
                    break;
                }
            }
        }
        ReadCardRecord readCardRecord = new ReadCardRecord();
        if (!CommonUtil.isHelpType(recordType)) {
            String time = DateFormatUtil.convertMillisecondsToStr(
                    System.currentTimeMillis(), "HH:mm:ss");
            msg = time + ":" + msg;
        }
        readCardRecord.setMsg(msg);
        readCardRecord.setRecordType(recordType);
        int index = 0;
        for (ReadCardRecord r : recordList) {
            if (CommonUtil.isHelpType(r.getRecordType())) {
                index++;
            }
        }
        recordList.add(index, readCardRecord);
//        if (fragmentReadSub != null) {
        // fragmentReadSub.mAdapter.notifyDataSetChanged();
//        }
    }

    public void sendCommandForBackward() {
        if (mBluetoothHelper != null && mBluetoothHelper.isConn) {
            mBluetoothHelper.sendCommand(BluetoothCommand.BACKWARD);
        }
//        else {
//            mUsbHelper.sendCommand(BluetoothCommand.BACKWARD);
//        }
    }

    public void sendCommandForForward() {
        if (mBluetoothHelper != null && mBluetoothHelper.isConn) {
            mBluetoothHelper.sendCommand(BluetoothCommand.FORWARD);
        }
//        else {
//            mUsbHelper.sendCommand(BluetoothCommand.FORWARD);
//        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 3) {
                mBluetoothHelper.connectBluetooth(this);
            } else if (requestCode == 0x210 || requestCode == 0x220) {
                if (data.getBooleanExtra(IntentUtil.SINGLE_UPLOAD, false)) {
                    mFragmentReadPaper.mSwipeRefreshLayout.setRefreshing(true);
                    mFragmentReadPaper.mRefreshListener.onRefresh();
                }
            }
        }
    }
}